package beusoft.ccjk.com.proxy;

import android.app.Activity;
import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by CCJK on 2017/12/3.
 */

public class InstrumentationProxy extends Instrumentation {
    Instrumentation instrumentation;
    Method execStartActivityMethod;
    public InstrumentationProxy(Instrumentation instrumentation) {
        this.instrumentation = instrumentation;
        initMethod();

    }

    @Override
    public void onCreate(Bundle arguments) {
        super.onCreate(arguments);
    }


    private void initMethod(){
        try {
            Class<?> clazz=instrumentation.getClass();
            execStartActivityMethod=clazz.getMethod("execStartActivity",new Class[]{Context.class,IBinder.class,IBinder.class
                    ,Activity.class,Intent.class,int.class,Bundle.class});
            execStartActivityMethod.setAccessible(true);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }



    public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {

        ActivityResult result = null;
        before();
        try {
            result= (ActivityResult) execStartActivityMethod.invoke(instrumentation,who,contextThread,token,target,intent,requestCode,options);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        after();
        return result;
    }

    private void after() {
        Log.e("HotPlugin", "after");
    }

    private void before() {
        Log.e("HotPlugin", "before");
    }


}
